//
// Created by ta&to on 2022/10/9.
//

#ifndef HTTPSERVER_HTTP_HANDLER_H
#define HTTPSERVER_HTTP_HANDLER_H
#include "hash_util.h"
#include "core.h"
#include "http_io.h"

#define FD_UNUSE    0
#define FD_USE      1

typedef struct http_fd_s http_fd_t;
typedef struct http_handler_s http_handler_t;
typedef struct http_inner_request_before_facade_s http_inner_request_before_facade_t;
typedef struct http_inner_request_after_facade_s http_inner_request_after_facade_t;
typedef struct http_inner_response_before_facade_s http_inner_response_before_facade_t;
typedef struct http_inner_response_after_facade_s http_inner_response_after_facade_t;
typedef void (*http_callback_func)(http_inner_request_after_facade_t *hirqaft);

struct body_stream_t {
    int read_end;   // 报文是否已经读完
    int reading;    // 是否正在读取数据
    int need_read_len; // 本次任务需要读多少字段
    int has_readed; // 本次任务已读多少字段
    int remaining_read // 本次任务还有多少字段需要读
};

typedef struct request_head_attr_s {
    dts Method;
    dts path;
    dts Cache_control;
    dts User_Agent;
    dts Accept;
    dts Accept_Language;
    dts Accept_encoding;
    dts Host;
    dts Connection;
    int Content_Length;
    dts Content_Type;
    dts Origin;
    dts Referer;
} req_attr_t;

typedef struct response_head_attr_s {
    dts version;
    int status;
    dts success;
    dts Server;
    dts Date;
    dts Content_Type;
    dts Last_Modified;
    dts Transfer_Encoding;
    dts Connection;
    dts Vary;
    dts ETag;
    dts Content_Encoding;
    int Content_Length;
    dts Accept_Ranges;
} rep_attr_t ;

typedef struct http_pool_s{
    pthread_mutex_t http_mut_lock;
    pthread_rwlock_t http_rw_lock;
} http_pool_t;

struct http_fd_s{
    int fd;
    char *fdc;
    unsigned int state;
    pthread_mutex_t lock;                       // 文件描述符锁 对文件描述符的读写操作都要加锁
};

struct http_handler_s{
    http_callback_func func;
};

struct http_event_context_control_s {
    http_handler_t *func_handler;
};

struct http_inner_request_before_facade_s{
    http_fd_t *fds;
    struct http_socket_event_s *hset;
};

struct http_inner_request_after_facade_s{
    http_fd_t *fds;
    struct http_socket_event_s *hset;
};

struct http_inner_response_before_facade_s{
    int fd;
    rep_attr_t *attr;
    struct req_header_s *rh;
};

struct http_inner_response_after_facade_s{

};

static inline void dts_free_null(dts *src){
    if(*src) {
        dtsfree(*src);
    }
    *src = NULL;
}
static inline void dts_auto_make(dts *desc, dts src) {
    if(*desc) {
        dts_free_null(desc);
    }
    *desc = src;
}
#endif //HTTPSERVER_HTTP_HANDLER_H
